import { constantRoutes, keyRoutes } from '@/router'
import { currentMenu } from '@/api/menu.js'

const state = {
  routes: [],
  addRoutes: null
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

/**
 * meta 元数据
 *
      title: 标题,
      icon: 图标,
      apis:权限,
      noCache: 不缓存,
      affix: 标签固定,
      breadcrumb: 加入面包屑
 *
 */
function buildAsyncRoutes(menus = [], keyRoutes = {}, pPath = '', level) {
  level = level + 1
  if (menus.length === 0) {
    return []
  }
  if (Object.keys(keyRoutes).length === 0) {
    return []
  }
  const routes = []
  for (let index = 0; index < menus.length; index++) {
    const menu = menus[index]
    const route = {}
    const routeKey = menu.routeKey
    if (!routeKey) {
      continue
    }
    const title = menu.title
    if (!title) {
      continue
    }
    const meta = JSON.parse(menu.meta || '{}')
    const componentKey = meta.componentKey
    if (!componentKey) {
      continue
    }
    route.name = componentKey
    route.path = pPath + '/' + routeKey

    const component = keyRoutes[meta.componentKey || '']
    if (!component) {
      continue
    }
    route.component = component

    route.meta = {
      title: title,
      icon: meta.icon || 'dashboard',
      apis: menu.apiUrls || [],
      noCache: !meta.cache,
      affix: meta.affix,
      breadcrumb: meta.breadcrumb
    }
    const childrens = buildAsyncRoutes(menu.childrens || [], keyRoutes, route.path, level)
    route.children = childrens
    if (childrens.length > 0) {
      route.redirect = childrens[0].path
      route.meta.affix = false
      if (level > 1) {
        route.component = keyRoutes['main-view']
        route.name = 'main-view'
      }
      if (level === 1) {
        route.component = keyRoutes['layout']
        route.name = 'layout'
      }
    }
    routes.push(route)
  }
  return routes
}

const actions = {
  generateRoutes({ commit, state }, roles) {
    if (state.addRoutes) {
      return new Promise(resolve => {
        resolve(state.addRoutes)
      })
    }
    return currentMenu({ platformCode: 'MANAGER-SYSTEM' }).then(rsp => {
      if (rsp.data) {
        const accessedRoutes = buildAsyncRoutes(rsp.data, keyRoutes, '', 0)
        let routes = [...accessedRoutes]
        if (routes.length > 0) {
          routes = [{
            path: '/',
            component: keyRoutes['layout'],
            redirect: routes[0].path
          }, ...routes]
        }
        commit('SET_ROUTES', routes)
        return routes
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
